package net.dreamlu.controller.admin;

import com.jfinal.aop.Before;

import net.dreamlu.common.WebUtils;
import net.dreamlu.ext.base.BaseController;
import net.dreamlu.interceptor.AdminInterceptor;
import net.dreamlu.model.User;
import net.dreamlu.vo.AjaxResult;

/**
 * 后台用户管理
 * @author L.cm
 * @date 2013-5-31 下午9:52:04
 */
@Before(AdminInterceptor.class)
public class AdminUserController extends BaseController {

	public void index() {
		User user = WebUtils.currentUser(this);
		user = User.dao.findById(user.getId());
		setAttr("userInfo", user);
	}

	// 更新用户信息
	public void update() {
		// session 中的 user 避免用户修改id
		User sessionUser = WebUtils.currentUser(this);
		User user = getModel(User.class);
		user.setId(sessionUser.getId());
		renderJson(new AjaxResult(user.update()));
	}

	// 列表页
	public void list() {}

	// DataTable
	public void list_json() {
		User user = WebUtils.currentUser(this);
		
		int iDisplayStart = getParaToInt("iDisplayStart", 0);
		int pageSize = getParaToInt("iDisplayLength", 10);
		int pageNum =  iDisplayStart / pageSize + 1;
		String search = getPara("sSearch");
		
		renderDataTable(User.dao.pageDataTables(pageNum, pageSize, search, user.getId()));
	}

	// 更新状态
	public void update_status() {
		User admin = WebUtils.currentUser(this);
		if (User.V_A != admin.getAuthority()) {
			AjaxResult result = new AjaxResult().addError("你没有权限！");
			renderJson(result);
			return;
		}
		User user = User.dao.findById(getParaToInt());
		if (user.getId() == admin.getId()) {
			AjaxResult result = new AjaxResult().addError("请不要修改管理员的权限！");
			renderJson(result);
			return;
		}
		int status = user.getDelStatus();
		user.setStatus(status == 1 ? 0 : 1);
		boolean temp = user.update();
		renderJson(new AjaxResult(temp));
	}

	// 更新角色
	public void update_role() {
		User admin = WebUtils.currentUser(this);
		if (User.V_A != admin.getAuthority()) {
			AjaxResult result = new AjaxResult().addError("你没有权限！");
			renderJson(result);
			return;
		}
		int role = getParaToInt("role");
		if (role < 0 || role > 2) {
			AjaxResult result = new AjaxResult().addError("不存在该权限！");
			renderJson(result);
			return;
		}
		User user = User.dao.findById(getParaToInt());
		if (user.getId() == admin.getId()) {
			AjaxResult result = new AjaxResult().addError("请不要修改管理员的权限！");
			renderJson(result);
			return;
		}
		user.setAuthority(role);
		boolean temp = user.update();
		renderJson(new AjaxResult(temp));
	}
}
